package org.ysling.litemall.core.tasks.impl;
/**
 *  Copyright (c) [ysling] [927069313@qq.com]
 *  [litemall-plus] is licensed under Mulan PSL v2.
 *  You can use this software according to the terms and conditions of the Mulan PSL v2.
 *  You may obtain a copy of Mulan PSL v2 at:
 *              http://license.coscl.org.cn/MulanPSL2
 *  THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 *  EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 *  MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 *  See the Mulan PSL v2 for more details.
 */
import lombok.extern.slf4j.Slf4j;
import org.ysling.litemall.core.service.ActionLogService;
import org.ysling.litemall.core.service.OrderCoreService;
import org.ysling.litemall.core.system.SystemConfig;
import org.ysling.litemall.core.tasks.service.Task;
import org.ysling.litemall.core.utils.BeanUtil;
import org.ysling.litemall.db.constant.OrderConstant;
import org.ysling.litemall.db.domain.LitemallOrder;
import org.ysling.litemall.db.service.*;

/**
 * 订单超时支付延时队列
 */
@Slf4j
public class OrderUnpaidTask extends Task {
    
    private final Integer orderId;

    public OrderUnpaidTask(Integer orderId, long delayInMilliseconds){
        super("OrderUnpaidTask-" + orderId, delayInMilliseconds);
        this.orderId = orderId;
    }

    public OrderUnpaidTask(Integer orderId){
        super("OrderUnpaidTask-" + orderId, SystemConfig.getOrderUnpaid() * 60 * 1000);
        this.orderId = orderId;
    }

    @Override
    public void run() {
        log.info(String.format("系统处理延时任务 -> [开始-订单超时未付款] [任务ID-%s]" , this.orderId));

        ActionLogService logService = BeanUtil.getBean(ActionLogService.class);
        OrderCoreService orderCoreService = BeanUtil.getBean(OrderCoreService.class);
        LitemallOrderService orderService = BeanUtil.getBean(LitemallOrderService.class);

        logService.logOrderSucceed("系统处理延时任务",String.format("[开始-订单超时未付款] [任务ID-%s]" , this.orderId));

        LitemallOrder order = orderService.findById(this.orderId);
        if(order == null || !OrderConstant.isCreateStatus(order)) {
            return;
        }

        // 设置订单已取消状态
        order.setOrderStatus(OrderConstant.STATUS_AUTO_CANCEL);
        if (orderService.updateVersionSelective(order) == 0) {
            throw new RuntimeException("网络繁忙，请刷新重试");
        }

        // 返还订单
        orderCoreService.orderRelease(order);

        log.info(String.format("系统处理延时任务 -> [结束-订单超时未付款] [任务ID-%s]" , this.orderId));
        logService.logOrderSucceed("系统处理延时任务",String.format("[结束-订单超时未付款] [任务ID-%s]" , this.orderId));
    }
}
